package com.wmzdq.photocenter.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class PropertyUtil {
	private Logger  log=LoggerFactory.getLogger(PropertyUtil.class);
	
	private Properties pro;
	
	public PropertyUtil() throws FileNotFoundException{
		InputStream in;
		String os = System.getProperty("os.name");  
		if(!os.toLowerCase().startsWith("win")){  
			in= new FileInputStream("/lxy/messages.properties");
		}else{
			in = this.getClass().getResourceAsStream("/messages.properties");
		}
		pro = new Properties();
		 try {
			pro.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("加载配置错误",e);
		}
		//properties.getProperty("property_name");
	}
	
	public String get(String key){
		return pro.getProperty(key,"");
	}
	
	public boolean set(String key,String value){
		 pro.setProperty(key,value);
		 //pro.
		 try{
			 FileOutputStream fos ;
			 String os = System.getProperty("os.name");  
			if(!os.toLowerCase().startsWith("win")){  
				fos = new FileOutputStream(new File("/lxy/messages.properties"));
			}else{
				URL fileUrl = this.getClass().getResource("/messages.properties");//得到文件路径
		        fos = new FileOutputStream(new File(fileUrl.toURI()));
			}
			 pro.store(fos,"");
			 fos.close();
			 return true;
		 }catch(Exception e){
			 log.error("保存配置失败",e);
			 return false;
		 }
		
	}
	
	public String[] keys(){
		ArrayList list=Collections.list(pro.keys());
		String[] str=new String[list.size()];
		int i=0;
		for (Object object : list) {
			str[i]=object.toString();
			i++;
		}
		
		return str;
	}
	
	public String getKeyByVal(String value){
		  Iterator<Entry<Object, Object>> it = pro.entrySet().iterator();  
	        while (it.hasNext()) {  
	            Entry<Object, Object> entry = it.next();  
	            Object key = entry.getKey();  
	            Object val = entry.getValue();  
	            if(value.equals(val.toString()))
	            	return (String) key;
	        }
	        return "";
		
	}

}
